package net.itgoo.parkingpay.ui.recordin;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import net.itgoo.parkingpay.rest.ParkingVolleyManager;
import net.itgoo.parkingpay.rest.model.ParkingRecordModel;
import net.itgoo.parkingpay.vendor.mvp.ParkingMVPLoadDataCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ParkingRecordInDataRepository implements ParkingRecordInContract.DataSource {

    private List<ParkingRecordModel> mData = new ArrayList<>();

    @Override
    public void refresh(String userId, String plate, final ParkingMVPLoadDataCallback callback) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("plate", plate);
            jsonObject.put("appuserid", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ParkingVolleyManager.sendJsonObjectRequest(Request.Method.POST,
                ParkingVolleyManager.baseUrl + "App_getRecordInList.do", jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        mData.clear();
                        try {
                            JSONArray array = response.getJSONArray("list");
                            for (int i = 0; i < array.length(); ++i) {
                                JSONObject obj = array.getJSONObject(i);
                                mData.add(ParkingRecordModel.parse(obj));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        callback.onDataLoaded(mData);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callback.onDataError(error.getMessage());
                    }
                });
    }

    @Override
    public void loadMore(ParkingMVPLoadDataCallback callback) {

    }

    @Override
    public ParkingRecordModel value(int position) {
        if (position >= 0 && position < mData.size()) {
            return mData.get(position);
        }
        return null;
    }

    @Override
    public void cancel() {

    }
}
